const express = require('express');
const router = express.Router();
const axios = require('axios');
const crypto = require('crypto');
const path = require('path');
const { query } = require('../rds');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });

// ERP配置
const erpConfig = {
    appKey: process.env.ERP_APP_KEY || '',
    appSecret: process.env.ERP_APP_SECRET || '',
    accessToken: process.env.ERP_ACCESS_TOKEN || '',
    refreshToken: process.env.ERP_REFRESH_TOKEN || '',
    apiUrl: 'https://openapi.jushuitan.com',
    // 订单状态映射
    orderStatus: {
        WAIT_PAY: '待付款',
        WAIT_SEND: '待发货',
        WAIT_RECEIVE: '待收货',
        COMPLETE: '已完成',
        CLOSED: '已关闭',
        REFUNDING: '退款中',
        REFUNDED: '已退款'
    },
    // 异常类型映射
    questionTypes: {
        Price: '价格异常',
        Address: '地址异常',
        Phone: '电话异常',
        Other: '其他异常'
    }
};

class ErpController {
    constructor() {
        this.appKey = erpConfig.appKey;
        this.appSecret = erpConfig.appSecret;
        this.accessToken = erpConfig.accessToken;
        this.apiUrl = erpConfig.apiUrl;
        this.orderStatus = erpConfig.orderStatus;
        this.questionTypes = erpConfig.questionTypes;

        // 绑定方法到实例
        this.getSign = this.getSign.bind(this);
        this.requestPost = this.requestPost.bind(this);
        this.test = this.test.bind(this);
        this.getOrderList = this.getOrderList.bind(this);
        this.getShopList = this.getShopList.bind(this);
        this.ordersUpload = this.ordersUpload.bind(this);
        this.cancelOrder = this.cancelOrder.bind(this);
        this.questionOrder = this.questionOrder.bind(this);
    }

    // 获取签名
    getSign(appSecret, data) {
        if (!data) return null;

        const sortedData = Object.keys(data)
            .sort()
            .reduce((acc, key) => {
                if (key !== 'sign' && key !== null && key !== '') {
                    acc[key] = data[key];
                }
                return acc;
            }, {});

        const resultStr = appSecret + Object.entries(sortedData)
            .map(([key, val]) => key + val)
            .join('');

        return crypto.createHash('md5')
            .update(resultStr)
            .digest('hex');
    }

    // 发送POST请求
    async requestPost(url, params) {
        try {
            const response = await axios.post(url, params, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });
            return response.data;
        } catch (error) {
            console.error('ERP API请求错误:', error.message);
            throw error;
        }
    }

    // 测试接口
    async test(req, res) {
        res.json({ msg: 'okey' });
    }

    // 获取订单列表
    async getOrderList(req, res) {
        try {
            const url = `${this.apiUrl}/open/orders/single/query`;

            // 获取订单号参数，支持单个或多个订单号（用逗号分隔）
            const oIds = (req.query.o_ids || '73932252')
                .split(',')
                .map(id => parseInt(id.trim()))
                .filter(id => !isNaN(id));

            if (oIds.length === 0) {
                return res.status(400).json({
                    error: '无效的订单号参数',
                    msg: '请提供有效的订单号，多个订单号用逗号分隔'
                });
            }

            const bizData = {
                o_ids: oIds,
                page_index: 1,
                page_size: 100
            };

            const data = {
                biz: JSON.stringify(bizData),
                charset: 'utf-8',
                access_token: this.accessToken,
                timestamp: Math.floor(Date.now() / 1000),
                version: '2',
                app_key: this.appKey
            };

            data.sign = this.getSign(this.appSecret, data);

            const result = await this.requestPost(url, data);
            res.json(result);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }

    // 获取店铺列表
    async getShopList(req, res) {
        try {
            const url = `${this.apiUrl}/open/shops/query`;

            const bizData = {
                page_no: 1,
                page_size: 50
            };

            const data = {
                biz: JSON.stringify(bizData),
                charset: 'utf-8',
                access_token: this.accessToken,
                timestamp: Math.floor(Date.now() / 1000),
                version: '2',
                app_key: this.appKey
            };

            data.sign = this.getSign(this.appSecret, data);

            const result = await this.requestPost(url, data);
            res.json(result);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }

    // 上传订单
    async ordersUpload(req, res) {
        try {
            const { order_id } = req.body;
            const url = `${this.apiUrl}/open/jushuitan/orders/upload`;

            // TODO: 实现订单数据转换
            const bizData = {};

            const data = {
                biz: JSON.stringify(bizData),
                charset: 'utf-8',
                access_token: this.accessToken,
                timestamp: Math.floor(Date.now() / 1000),
                version: '2',
                app_key: this.appKey
            };

            data.sign = this.getSign(this.appSecret, data);

            const result = await this.requestPost(url, data);
            res.json(result);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }

    // 取消订单
    async cancelOrder(req, res) {
        try {
            const { order_id } = req.body;
            const url = `${this.apiUrl}/open/jushuitan/orderbyoid/cancel`;

            const bizData = {
                cancel_type: '客户已退款',
                o_ids: [order_id]
            };

            const data = {
                biz: JSON.stringify(bizData),
                charset: 'utf-8',
                access_token: this.accessToken,
                timestamp: Math.floor(Date.now() / 1000),
                version: '2',
                app_key: this.appKey
            };

            data.sign = this.getSign(this.appSecret, data);

            const result = await this.requestPost(url, data);
            res.json(result);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }

    // 订单转异常
    async questionOrder(req, res) {
        try {
            const { order_id, question_type, question_desc, question_remark } = req.body;
            const url = `${this.apiUrl}/open/webapi/orderapi/questionorder/questions`;

            const bizData = {
                o_ids: [order_id],
                question_type: question_type || 'Price',
                question_desc: question_desc || '',
                question_remark: question_remark || '需要客服联系买家确认完整地址'
            };

            const data = {
                biz: JSON.stringify(bizData),
                charset: 'utf-8',
                access_token: this.accessToken,
                timestamp: Math.floor(Date.now() / 1000),
                version: '2',
                app_key: this.appKey
            };

            data.sign = this.getSign(this.appSecret, data);

            const result = await this.requestPost(url, data);
            res.json(result);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }

    // 处理ERP系统回调
    async handleErpCallback(req, res) {
        try {
            const data = req.body;
            const ip = req.ip;
            const url = req.originalUrl;
            const now = Math.floor(Date.now() / 1000);
            const code = 200;

            // 记录回调数据
            const dataJson = JSON.stringify(data);
            const resData = { code: 0, msg: '执行成功', time: now.toString() };
            const resJson = JSON.stringify(resData);

            // 处理物流状态更新
            if (data.partnerid === 'erp' && data.method === 'logistics.upload') {
                const erpOrderCode = data.o_id.toString();
                const soId = data.so_id;

                if (soId) {
                    // 查询订单

                    // 更新订单信息

                    // TODO: 发送微信通知
                    // await WechatService.sendBotNotice(remark);
                }
            }

            // 记录回调日志

            res.json(resData);
        } catch (error) {
            console.error('ERP回调处理错误:', error);
            res.status(500).json({
                code: 500,
                msg: '处理失败',
                error: error.message
            });
        }
    }

    // 处理订单取消回调
    async handleOrderCancelCallback(req, res) {
        try {
            const data = req.body;
            const ip = req.ip;
            const url = req.originalUrl;
            const now = Math.floor(Date.now() / 1000);
            const code = 200;

            // 记录回调数据
            const dataJson = JSON.stringify(data);
            const resData = { code: 0, msg: '执行成功', time: now.toString() };
            const resJson = JSON.stringify(resData);

            if (data.partnerid === 'erp' && data.method === 'order.cancel') {
                const erpOrderCode = data.o_id.toString();
                const soId = data.so_id;

                if (soId) {
                    // TODO: 实现订单取消逻辑
                    // 1. 更新订单状态
                    // 2. 处理库存
                    // 3. 发送通知
                }
            }

            // 记录回调日志

            res.json(resData);
        } catch (error) {
            console.error('订单取消回调处理错误:', error);
            res.status(500).json({
                code: 500,
                msg: '处理失败',
                error: error.message
            });
        }
    }

    // 处理库存同步回调
    async handleInventorySyncCallback(req, res) {
        try {
            const data = req.body;
            const ip = req.ip;
            const url = req.originalUrl;
            const now = Math.floor(Date.now() / 1000);
            const code = 200;

            // 记录回调数据
            const dataJson = JSON.stringify(data);
            const resData = { code: 0, msg: '执行成功', time: now.toString() };
            const resJson = JSON.stringify(resData);

            if (data.partnerid === 'erp' && data.method === 'business_sku_syc') {
                const skuList = data.sku_list || [];

                console.log('收到库存同步消息:');
                console.log('消息ID:', data.msg_id);
                console.log('消息类型:', data.msg_type);
                console.log('消息时间:', data.msg_time);
                console.log('店铺ID:', data.shop_id);
                console.log('店铺名称:', data.shop_name);
                console.log('商品列表:', JSON.stringify(skuList, null, 2));

                for (const sku of skuList) {
                    console.log('处理商品:', {
                        '商品编码': sku.sku_id,
                        '商品名称': sku.name,
                        '规格编码': sku.spec_id,
                        '规格名称': sku.spec_name,
                        '库存数量': sku.qty,
                        '可用库存': sku.available_qty,
                        '锁定库存': sku.lock_qty,
                        '在途库存': sku.transit_qty,
                        '更新时间': sku.modified
                    });

                    // TODO: 实现库存同步逻辑
                    // 1. 更新商品库存
                    // 2. 记录库存变更日志
                    // 3. 发送库存预警通知
                }
            }

            res.json(resData);
        } catch (error) {
            console.error('库存同步回调处理错误:', error);
            res.status(500).json({
                code: 500,
                msg: '处理失败',
                error: error.message
            });
        }
    }

    // 处理售后消息回调
    async handleAfterSalesCallback(req, res) {
        try {
            const data = req.body;
            const ip = req.ip;
            const url = req.originalUrl;
            const now = Math.floor(Date.now() / 1000);
            const code = 200;

            // 记录回调数据
            const dataJson = JSON.stringify(data);
            const resData = { code: 0, msg: '执行成功', time: now.toString() };
            const resJson = JSON.stringify(resData);

            if (data.partnerid === 'erp' && data.method === 'trade_after_sales') {
                const afterSalesList = data.after_sales_list || [];

                console.log('收到售后消息:');
                console.log('消息ID:', data.msg_id);
                console.log('消息类型:', data.msg_type);
                console.log('消息时间:', data.msg_time);
                console.log('店铺ID:', data.shop_id);
                console.log('店铺名称:', data.shop_name);
                console.log('售后列表:', JSON.stringify(afterSalesList, null, 2));

                for (const afterSales of afterSalesList) {
                    console.log('处理售后:', {
                        '售后单号': afterSales.as_id,
                        '订单编号': afterSales.o_id,
                        '售后类型': afterSales.type,
                        '售后状态': afterSales.status,
                        '退款金额': afterSales.refund_fee,
                        '退款状态': afterSales.refund_status,
                        '退货状态': afterSales.return_status,
                        '创建时间': afterSales.created,
                        '更新时间': afterSales.modified
                    });

                    // TODO: 实现售后处理逻辑
                    // 1. 更新订单售后状态
                    // 2. 处理退款/退货流程
                    // 3. 发送售后状态通知
                }
            }

            res.json(resData);
        } catch (error) {
            console.error('售后消息回调处理错误:', error);
            res.status(500).json({
                code: 500,
                msg: '处理失败',
                error: error.message
            });
        }
    }
}

const erpController = new ErpController();

// ERP接口路由
router.get('/test', erpController.test);
router.get('/orders', erpController.getOrderList);
router.get('/shops', erpController.getShopList);
router.post('/orders/upload', erpController.ordersUpload);
router.post('/orders/cancel', erpController.cancelOrder);
router.post('/orders/question', erpController.questionOrder);

// ERP回调接口路由
router.post('/callback', erpController.handleErpCallback);
router.post('/callback/logistic', erpController.handleErpCallback);
router.post('/callback/cancel', erpController.handleOrderCancelCallback);
router.post('/callback/inventory', erpController.handleInventorySyncCallback);
router.post('/callback/after-sales', erpController.handleAfterSalesCallback);

module.exports = router;
